package com.jwtItem.JWTConfig;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * 配置jwt
 */
public class JWTUtils {
    /*
     *声明密匙  此处是自己写的
     */
    private static String TOKEN = "token!@#$%213";


    /**
     * 生成token  header.payload.sing
     */
    public static String getToken(Map<String, String> map) {
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 7);//过期时间 7天
        //创建jwt builder
        final JWTCreator.Builder builder = JWT.create();
        //payload
        map.forEach((k, v) -> {
            builder.withClaim(k, v);
        });

        String token = builder.withExpiresAt(instance.getTime()).sign(Algorithm.HMAC256(TOKEN));
        return token;
    }

    /**
     * 验证token 合法性
     * - SignatureVerificationException: 签名不-致异常
     * - TokenExpiredException:  令牌过期异常
     * - AlgorithmMismatchException:  算法不匹配异常
     * - InvalidClaimException:   失效的payload异常
     */
    public static void verify(String token) {
        JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }


    /**
     *获取token中的payload
     */
    public  static DecodedJWT getToken(String token){
        return  JWT.require(Algorithm.HMAC256(TOKEN)).build().verify(token);
    }



}
